package com.mobile.collect.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;

import com.mobile.collect.R;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.view.MyPointView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import cn.droidlover.xdroidmvp.kit.CrashHandler;
import cn.droidlover.xdroidmvp.kit.NLog;

public class ExportPicUtil {
    Activity mContext;
    int width;
    int height;
    int imageBitmapWidth;
    int imageBitmapHeight;

    int resultBitmapWidth;
    int resultBitmapHeight;
//    Bitmap resourceBitmap;
    float pointDx;
    int minX = 0;
    int maxX = 0;
    int minY = 0;
    int maxY = 0;


    public ExportPicUtil(Activity mContext) {
        this.mContext = mContext;
        DisplayMetrics dm = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;
        height = dm.heightPixels;
        writeRecord("当前手机的宽度 =" + width);
        writeRecord("当前手机的高度 =" + height);
    }


    public String save2File(DevicePicInfo picInfo, String dir, String fileName) {
        int picBitMapWidth = picInfo.getPicBitMapWidth();
        int picBitMapHeight = picInfo.getPicBitmapHeight();
        countImageBitmap(picBitMapWidth, picBitMapHeight, picInfo.getPicPath());
        countPointPosition(picInfo.getPointList());
        String filePath = "";
        try{
             filePath = draw(picInfo, dir, fileName);
        }catch (Exception ex){
            CrashHandler.getInstance().handleException(ex);
        }

        return filePath;
    }


    /**
     * 计算所有点的极限位置
     */
    private void countPointPosition(List<DevicePointInfo> list) {
        int iX = (width - imageBitmapWidth) / 2;
        int iY = (height - imageBitmapHeight) / 2;
        int[] pointPoints = new int[4];
        for (DevicePointInfo pointInfo : list) {
            NLog.d("saveFile", pointInfo.toString());
            double scaleX = pointInfo.getScaleX();
            double scaleY = pointInfo.getScaleY();

            int pointX = (int) (iX + width * scaleX);
            int pointY = (int) (iY + height * scaleY);


            NLog.e("TRANSFORM", "pointDx =" + pointDx);
            NLog.e("TRANSFORM", "oldWidth =" + pointInfo.getViewWidth());
            NLog.e("TRANSFORM", "oldHeigh =" + pointInfo.getViewHeight());

            writeRecord("转换后点的 screenX =" + pointX);
            writeRecord("转换后点的 screenY =" + pointY);
            pointInfo.setRealScreenX(pointX);
            pointInfo.setRealSCreenY(pointY);

            int newWidth = (int) (pointInfo.getViewWidth() / pointDx);
            int newHeigh = (int) (pointInfo.getViewHeight() / pointDx);
            pointInfo.setRealViewWidth(newWidth);
            pointInfo.setRealViewHeight(newHeigh);

            writeRecord("转换后点的 newWidth =" + newWidth);
            writeRecord("转换后点的 newHeigh =" + newHeigh);


            if (pointInfo.getDirection() == 0) {
                pointX = pointX + newWidth;
            }

            if (pointInfo.getDirection() == 90) {
                pointY = pointY + newHeigh;
            }

            if (minX > pointX || minX == 0) {
                minX = pointX;
            }

            if (maxX < pointX) {
                maxX = pointX;
            }

            if (minY == 0 || minY > pointY) {
                minY = pointY;
            }

            if (maxY < pointY) {
                maxY = pointY;
            }
        }
        resultBitmapWidth = width;
        resultBitmapHeight = height;

        if (maxX > width) {
            if (minX < 0) {
                resultBitmapWidth = maxX - minX;
            } else {
                resultBitmapWidth = maxX;
            }
        } else {
            if (minX < 0) {
                resultBitmapWidth = width - minX;
            } else {
                resultBitmapWidth = width;
            }
        }

        if (maxY > height) {
            if (minY < 0) {
                resultBitmapHeight = maxY - minY;
            } else {
                resultBitmapHeight = maxY;
            }
        } else {
            if (minY < 0) {
                resultBitmapHeight = height - minY;
            } else {
                resultBitmapHeight = height;
            }
        }



    }

    private void countImageBitmap(int picBitMapWidth, int picBitMapHeight, String picPath) {
        NLog.e("ExportUtil", "saveFile =");


        float dx = picBitMapWidth * 1.0f / picBitMapHeight;
        writeRecord("APP原始图片的长宽比例 =" + dx);

        imageBitmapWidth = width;
        imageBitmapHeight = (int) (width / dx);

//        writeRecord("新图片的宽度 =" + resultBitMapWeith);
//        writeRecord("新图片的高度 =" + resultBitMapHeight);

        pointDx = picBitMapWidth * 1.0f / width;
        writeRecord("新图片BitMap的宽度 =" + imageBitmapWidth);
        writeRecord("新图片BitMap的高度 =" + imageBitmapHeight);
    }

    private String draw(DevicePicInfo picInfo, String dir, String fileName) throws Exception {
        Bitmap resultBitmap = Bitmap.createBitmap(resultBitmapWidth, resultBitmapHeight, Bitmap.Config.ARGB_8888);

        Bitmap initBitmap = getBitmapFromUri(mContext, picInfo.getPicPath());
        Bitmap resourceBitmap = Bitmap.createScaledBitmap(initBitmap, imageBitmapWidth, imageBitmapHeight, true);

        Canvas canvas = new Canvas(resultBitmap);

        int imagePositionX;
        int imagePositionY;

        if (resultBitmapWidth > width) {
            if (minX < 0) {
                imagePositionX = (width - imageBitmapWidth) / 2 + Math.abs(minX);
            } else {
                imagePositionX = (width - imageBitmapWidth) / 2;
            }
        } else {
            imagePositionX = (width - imageBitmapWidth) / 2;
        }


        if (resultBitmapHeight > height) {
            if (minY < 0) {
                imagePositionY = (height - imageBitmapHeight) / 2 + Math.abs(minY);
            } else {
                imagePositionY = (height - imageBitmapHeight) / 2;
            }
        } else {
            imagePositionY = (height - imageBitmapHeight) / 2;
        }




        canvas.drawBitmap(resourceBitmap, imagePositionX, imagePositionY, null);

        for (DevicePointInfo pointInfo : picInfo.getPointList()) {

            if (pointInfo.getIsNewPoint()) {
                continue;
            }
            Bitmap childBitmap = getPoint(pointInfo, pointInfo.getRealViewWidth(), pointInfo.getRealViewHeight());
            int positionX = pointInfo.getRealScreenX();
            int positionY = pointInfo.getRealSCreenY();

            if (positionX > 0) {
                positionX = imagePositionX + positionX;
            } else {
                positionX = imagePositionX - Math.abs(positionX);
            }


            if (minY < 0) {
                positionY = imagePositionY + positionY;
            }

            writeRecord("点的实际坐标X =" + positionX);
            writeRecord("点的时间坐标Y =" + positionY);

            canvas.drawBitmap(childBitmap, positionX, positionY, null);
            childBitmap.recycle();
        }


        writeRecord("面板的宽度 =" + resultBitmap.getWidth());
        writeRecord("面板的高度 =" + resultBitmap.getHeight());

        Paint textPaint = new Paint();
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setColor(Color.RED);
        textPaint.setAntiAlias(true);
        textPaint.setDither(true);
        textPaint.setStrokeWidth(8);
        textPaint.setTextSize(50);
        textPaint.setTextAlign(Paint.Align.LEFT);
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();

        NLog.d("FontMetrics", "fontMetrics.top=" + fontMetrics.top);
        NLog.d("FontMetrics", "fontMetrics.bottom=" + fontMetrics.bottom);

        float distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
        canvas.drawText(fileName, imagePositionX + 20, imagePositionY + 40 + distance, textPaint);


        File newFile = new File(dir, fileName + ".jpeg");

        writeRecord("截取的起始点minY =" + minY);

        int cropX = 0;
        int cropY = 0;
        int cropWidth = 0;
        int cropHeigh = 0;


        if (minX < 0) {
            cropX = 0;
            if (maxX > imageBitmapWidth) {
                cropWidth = maxX + Math.abs(minX);
            } else {
                cropWidth = imageBitmapWidth + Math.abs(minX);
            }
        } else if (minX > 0 && minX < imagePositionX) {
            cropX = minX;
            if (maxX > imagePositionX + imageBitmapWidth) {
                cropWidth = maxX - Math.abs(minX);
            } else {
                cropWidth = imageBitmapWidth - Math.abs(minX);
            }
        } else {
            cropX = imagePositionX;
            if (maxX > imagePositionX + imageBitmapWidth) {
                cropWidth = maxX - cropX;
            } else {
                cropWidth = imageBitmapWidth;
            }
        }


        if (minY < 0) {
            cropY = 0;
            if (maxY > imageBitmapHeight) {
                cropHeigh = maxY + Math.abs(minY);
            } else {
                cropHeigh = imageBitmapHeight + Math.abs(minY);
            }
        } else if (minY > 0 && minY < imagePositionY) {
            cropY = minY;
            if (maxY > imageBitmapHeight+cropY) {
                cropHeigh = maxY - Math.abs(minY);
            } else {
                cropHeigh = imageBitmapHeight - Math.abs(minY);
            }
        } else {
            cropY = imagePositionY;
            if (maxY > imageBitmapHeight +cropY) {
                cropHeigh = maxY - cropY;
            } else {
                cropHeigh = imageBitmapHeight;
            }
        }

        NLog.d("saveFile", picInfo.getLabel() + " minY=" + minY + " maxY=" + maxY + " imageBitmapHeight=" + imageBitmapHeight + " resultBitmapHeight=" + resultBitmapHeight + " imagePositionY = " + imagePositionY);
        NLog.d("saveFile", picInfo.getLabel() + " cropX=" + cropX + " cropY=" + cropY + " cropWidth=" + cropWidth + " cropHeigh=" + cropHeigh);


        Bitmap result2Bitmap = null;
        try {
            result2Bitmap = Bitmap.createBitmap(resultBitmap, cropX, cropY, cropWidth, cropHeigh);
            saveBitmap(result2Bitmap, newFile);
            NLog.d("saveFile", picInfo.getDeviceName() + picInfo.getLabel() + "导出成功");
            writeRecord(picInfo.getDeviceName() + picInfo.getLabel() + "导出成功");
        } catch (Exception ex) {
            writeRecord(picInfo.getLabel() + "导出失败\n");
            NLog.d("saveFile", picInfo.getDeviceName() + picInfo.getDeviceName() + picInfo.getLabel() + "导出失败");
            ex.printStackTrace();
            CrashHandler.getInstance().handleException(ex);
            return "";

        } finally {
            if (initBitmap !=null && !initBitmap.isRecycled()) {
                initBitmap.recycle();
            }

            if (null != resourceBitmap && !resourceBitmap.isRecycled()) {
                resourceBitmap.recycle();
            }
            if (null != resultBitmap && !resultBitmap.isRecycled() ) {
                resultBitmap.recycle();
            }
            if (null != result2Bitmap && !result2Bitmap.isRecycled()) {
                result2Bitmap.recycle();
            }
        }
        return newFile.getPath();
    }


    public Bitmap getPoint(final DevicePointInfo pointInfo, int width, int height) {
        MyPointView view;
        String lineType = pointInfo.getLineType2();

        if (TextUtils.equals("1x", lineType)) {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point, null, false);
        } else if (TextUtils.equals("2x", lineType)) {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point2, null, false);
        } else if (TextUtils.equals("3x", lineType)) {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point3, null, false);
        } else {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point, null, false);
        }
        view.setPointInfo(pointInfo, false);

        return createBitmap3(view, width, height);
    }


    public Bitmap getBitmapFromUri(Context context, String outfile) {
        writeRecord("getBitmapFromUri:" + "\n" + outfile);
        try {
//            outfile = outfile.replace("/storage/emulated/0/", "file:///sdcard/");
//            Uri uri = Uri.parse(outfile);
            Uri imageUri;
            File iamgeFile = new File(outfile);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(context, mContext.getPackageName() + ".fileprovider", iamgeFile);
            } else {
                imageUri = Uri.fromFile(iamgeFile);
            }
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageUri);
            return bitmap;
        } catch (Exception e) {
            writeRecord("getBitmapFromUri:" + "\n" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public Bitmap createBitmap3(View v, int width, int height) {
        //测量使得view指定大小
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        v.measure(measuredWidth, measuredHeight);
        //调用layout方法布局后，可以得到view的尺寸大小
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        writeRecord("width =" + width + " v.width =" + v.getWidth() + " height=" + height + " v.height =" + v.getHeight());
        Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        v.draw(c);
//        bmp.recycle();
        return bmp;
    }

    public boolean saveBitmap(Bitmap bm, File f) {
        writeRecord("saveBitmap =");
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            return true;
        } catch (FileNotFoundException e) {
            writeRecord("saveBitmap--" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            writeRecord("saveBitmap--" + e.getMessage());
            e.printStackTrace();
        } finally {
            bm.recycle();
        }
        return false;
    }


    private void writeRecord(String message) {
        NLog.d("writeRecord", message);
    }
}
